<template>
  <div class="share-container">
    <!-- 分享链接列表 -->
    <div class="list-header" v-if="shareList.length > 0">
      <h3 class="list-title">我的分享链接</h3>
      <p class="list-description">管理您创建的所有文件分享链接</p>
    </div>

    <el-table
        :data="shareList"
        border
        stripe
        style="width: 100%; margin-bottom: 20px"
        :row-style="{ height: '52px' }"
        :header-cell-style="headerCellStyle"
        class="share-table"
    >
      <!-- 调整链接名称列宽度 -->
      <el-table-column
          prop="fileShareLinkId"
          label="链接名称"
          min-width="40"
          align="left"
      >
        <template #default="scope">
          <span class="link-name">{{ scope.row.fileShareLinkId }}</span>
        </template>
      </el-table-column>

      <el-table-column
          prop="fileName"
          label="文件名称"
          min-width="50"
          align="center"
          class-name="file-name-column"
      />

      <el-table-column
          prop="createdAt"
          label="创建时间"
          min-width="40"
          align="center"
      >
        <template #default="scope">
          {{ formatTime(scope.row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column
          prop="expiresAt"
          label="有效期"
          min-width="40"
          align="center"
      >
        <template #default="scope">
          {{ scope.row.expiresAt ? formatTime(scope.row.expiresAt) : '永久有效' }}
        </template>
      </el-table-column>

      <!-- 优化操作按钮样式 -->
      <el-table-column
          label="操作"
          min-width="auto"
          align="center"
          class-name="action-column"
      >
        <template #default="scope">
          <el-tooltip content="复制分享链接" placement="top">
            <el-button
                type="text"
                size="small"
                @click="handleCopyLink(scope.row)"
                class="copy-btn"
            >
              <el-icon class="icon-mr"><Link /></el-icon>
              <span>复制链接</span>
            </el-button>
          </el-tooltip>

          <el-tooltip content="删除分享链接" placement="top">
            <el-button
                type="text"
                size="small"
                @click="handleDelete(scope.row)"
                class="delete-btn"
            >
              <el-icon class="icon-mr"><Delete /></el-icon>
              <span>删除链接</span>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 优化空状态样式 -->
    <div class="empty-state" v-if="shareList.length === 0">
      <el-empty
          description="暂无分享链接"
          :image-size="120"
          class="empty-content"
      >
        <template #default>
          <p>您还没有创建任何文件分享链接</p>
          <p>上传文件后，您可以创建分享链接</p>
        </template>
      </el-empty>
    </div>

    <!-- 调整分页布局 -->
    <div class="pagination-container">
      <CustomPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          @page-change="loadFiles"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElMessageBox, ElTooltip } from 'element-plus'
import { loadFileShareLinkApi, deleteFileShareLinkApi } from '@/utils/API/file-share/index.js'
import { hideLoading, showLoading } from '@/utils/LoadingUtil.js'
import dayjs from 'dayjs'
import { Link, Delete } from '@element-plus/icons-vue'

// 分享列表数据
const shareList = ref([])
// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表头样式
const headerCellStyle = computed(() => ({})) // 保持原始逻辑

// 时间格式化函数
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 加载分享链接列表（优化total赋值）
const loadFiles = async () => {
  try {
    showLoading('加载分享链接中...')
    const res = await loadFileShareLinkApi({
      current: currentPage.value,
      size: pageSize.value
    })
    if (res.code === 200) {
      console.log(res)
      shareList.value = res.data.records
      total.value = res.data.records.length
    } else {
      ElMessage.error(res.msg || '加载分享链接失败')
    }
  } catch (error) {
    ElMessage.error('网络请求异常，请稍后重试')
  } finally {
    hideLoading()
  }
}

// 复制链接操作
const handleCopyLink = (row) => {
  navigator.clipboard.writeText("通过Cloud-Drive分享的文件：\n" +
      "Cloud-Drive内地址:" + row.fileId + " 提取码:" + row.extractCode + " 文件名称:" + row.fileName +
      " 复制这段内容后打开Cloud-Drive下载共享链接，操作更方便哦！")
      .then(() => ElMessage.success('链接已复制到剪贴板'))
      .catch(() => ElMessage.error('复制链接失败'))
}

// 删除链接逻辑
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除链接「${row.fileShareLinkId}」吗？`,
        '警告操作',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    showLoading('删除分享链接中...')
    const res = await deleteFileShareLinkApi(row.fileShareLinkId)
    if (res.code === 200) {
      ElMessage.success('分享链接删除成功')
      await loadFiles()
    } else {
      ElMessage.error(res.msg || '删除分享链接失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('网络请求异常，请稍后重试')
    }
  } finally {
    hideLoading()
  }
}

// 初始化加载数据
onMounted(() => loadFiles())
</script>

<style scoped>
.share-container {
  padding: 28px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.06);
}

.list-header {
  margin-bottom: 20px;
}

.list-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.list-description {
  font-size: 14px;
  color: #909399;
}

.share-table {
  --el-table-border-color: #ebeef5;
  --el-table-row-bg-color: #fafbff;
  --el-table-row-hover-bg-color: #f0f7ff;
  border-radius: 8px;
  overflow: hidden;
}

.el-table__header th {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 500;
  height: 46px;
}

.link-name {
  color: #409eff;
  cursor: pointer;
  font-weight: 500;
}

.file-name-column {
  font-weight: 400;
}

.action-column {
  padding: 0 12px;
}

.copy-btn {
  color: #409eff;
  margin-right: 16px;
}

.delete-btn {
  color: #f56c6c;
}

.icon-mr {
  margin-right: 4px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-content {
  width: 100%;
  max-width: 500px;
}

.empty-content p {
  margin: 6px 0;
  font-size: 14px;
  color: #909399;
}

.empty-action-btn {
  margin-top: 16px;
  padding: 10px 24px;
}

.pagination-container {
  margin-top: 24px;
  text-align: right;
  padding: 0 8px;
}

:deep(.el-empty__image) {
  max-width: 120px;
}

:deep(.el-empty__description) {
  margin-top: 10px;
}

:deep(.el-table__cell) {
  padding: 0 12px;
}
</style>